$(function() {
    // 初始化数据表格
    var thresholdTable = $('#thresholdTable').DataTable({
        responsive: true,
        dom: 'Bfrtip',
        buttons: [
            'copy', 'csv', 'excel'
        ],
        language: {
            "sProcessing": "处理中...",
            "sLengthMenu": "显示 _MENU_ 项结果",
            "sZeroRecords": "没有匹配结果",
            "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
            "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
            "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
            "sInfoPostFix": "",
            "sSearch": "搜索:",
            "sUrl": "",
            "sEmptyTable": "表中数据为空",
            "sLoadingRecords": "载入中...",
            "sInfoThousands": ",",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上页",
                "sNext": "下页",
                "sLast": "末页"
            }
        },
        columns: [
            { data: 'thresholdId' },
            { data: 'warehouseName' },
            { data: 'storageArea' },
            { 
                data: null,
                render: function(data) {
                    return data.minTemperature + ' ~ ' + data.maxTemperature;
                }
            },
            { 
                data: null,
                render: function(data) {
                    return data.minHumidity + ' ~ ' + data.maxHumidity;
                }
            },
            { 
                data: 'alarmLevel',
                render: function(data) {
                    if (data === '1') {
                        return '<span class="badge badge-info">轻微</span>';
                    } else if (data === '2') {
                        return '<span class="badge badge-warning">中等</span>';
                    } else {
                        return '<span class="badge badge-danger">严重</span>';
                    }
                }
            },
            { 
                data: 'notifyEnabled',
                render: function(data) {
                    if (data === '1') {
                        return '<span class="badge badge-success">已启用</span>';
                    } else {
                        return '<span class="badge badge-secondary">未启用</span>';
                    }
                }
            },
            { 
                data: 'notifyType',
                render: function(data) {
                    if (!data) return '';
                    
                    var types = data.split(',');
                    var result = [];
                    
                    if (types.includes('1')) {
                        result.push('<span class="badge badge-info">短信</span>');
                    }
                    if (types.includes('2')) {
                        result.push('<span class="badge badge-primary">邮件</span>');
                    }
                    if (types.includes('3')) {
                        result.push('<span class="badge badge-warning">系统通知</span>');
                    }
                    
                    return result.join(' ');
                }
            },
            { 
                data: 'createTime',
                render: function(data) {
                    return formatDateTime(data);
                }
            },
            {
                data: null,
                render: function(data) {
                    return '<button class="btn btn-xs btn-primary edit-btn" data-id="' + data.thresholdId + '">编辑</button> ' +
                           '<button class="btn btn-xs btn-danger delete-btn" data-id="' + data.thresholdId + '">删除</button>';
                }
            }
        ]
    });
    
    // 初始化选择器
    $('.selectpicker').selectpicker();
    
    // 加载仓库下拉框选项
    loadWarehouseOptions();
    
    // 仓库选择变更事件
    $('#warehouseSelect').on('change', function() {
        var warehouseId = $(this).val();
        loadThresholdList(warehouseId);
    });
    
    // 新增按钮点击事件
    $('#addBtn').on('click', function() {
        resetForm();
        $('#thresholdModalLabel').text('新增阈值设置');
        $('#thresholdModal').modal('show');
    });
    
    // 编辑按钮点击事件
    $('#thresholdTable').on('click', '.edit-btn', function() {
        var thresholdId = $(this).data('id');
        loadThresholdDetail(thresholdId);
    });
    
    // 删除按钮点击事件
    $('#thresholdTable').on('click', '.delete-btn', function() {
        var thresholdId = $(this).data('id');
        if (confirm('确定要删除该阈值设置吗？')) {
            deleteThreshold(thresholdId);
        }
    });
    
    // 保存按钮点击事件
    $('#saveBtn').on('click', function() {
        saveThreshold();
    });
    
    // 加载仓库选项
    function loadWarehouseOptions() {
        $.ajax({
            url: '/warehouse/list',
            type: 'GET',
            success: function(res) {
                if (res.code === 200) {
                    var options = '';
                    $.each(res.data, function(index, warehouse) {
                        options += '<option value="' + warehouse.warehouseId + '">' + warehouse.warehouseName + '</option>';
                    });
                    $('#warehouseSelect').append(options);
                    $('#warehouseId').append(options);
                    
                    // 如果有仓库，默认选中第一个并加载数据
                    if (res.data && res.data.length > 0) {
                        $('#warehouseSelect').val(res.data[0].warehouseId).trigger('change');
                    }
                }
            }
        });
    }
    
    // 加载阈值设置列表
    function loadThresholdList(warehouseId) {
        var url = '/warehouse/coldStorageThreshold/list';
        if (warehouseId) {
            url += '?warehouseId=' + warehouseId;
        }
        
        $.ajax({
            url: url,
            type: 'GET',
            success: function(res) {
                if (res.code === 200) {
                    thresholdTable.clear().rows.add(res.data).draw();
                }
            }
        });
    }
    
    // 加载阈值设置详情
    function loadThresholdDetail(thresholdId) {
        $.ajax({
            url: '/warehouse/coldStorageThreshold/' + thresholdId,
            type: 'GET',
            success: function(res) {
                if (res.code === 200) {
                    var data = res.data;
                    
                    // 填充表单
                    $('#thresholdId').val(data.thresholdId);
                    $('#warehouseId').val(data.warehouseId);
                    $('#storageArea').val(data.storageArea);
                    $('#minTemperature').val(data.minTemperature);
                    $('#maxTemperature').val(data.maxTemperature);
                    $('#minHumidity').val(data.minHumidity);
                    $('#maxHumidity').val(data.maxHumidity);
                    $('#alarmLevel').val(data.alarmLevel);
                    $('#notifyEnabled').val(data.notifyEnabled);
                    
                    // 处理多选
                    if (data.notifyType) {
                        $('#notifyType').selectpicker('val', data.notifyType.split(','));
                    } else {
                        $('#notifyType').selectpicker('deselectAll');
                    }
                    
                    $('#notifyReceivers').val(data.notifyReceivers);
                    $('#remark').val(data.remark);
                    
                    // 显示模态框
                    $('#thresholdModalLabel').text('编辑阈值设置');
                    $('#thresholdModal').modal('show');
                }
            }
        });
    }
    
    // 保存阈值设置
    function saveThreshold() {
        // 表单验证
        if (!$('#thresholdForm')[0].checkValidity()) {
            $('#thresholdForm')[0].reportValidity();
            return;
        }
        
        // 获取表单数据
        var formData = {
            thresholdId: $('#thresholdId').val(),
            warehouseId: $('#warehouseId').val(),
            warehouseName: $('#warehouseId option:selected').text(),
            storageArea: $('#storageArea').val(),
            minTemperature: $('#minTemperature').val(),
            maxTemperature: $('#maxTemperature').val(),
            minHumidity: $('#minHumidity').val(),
            maxHumidity: $('#maxHumidity').val(),
            alarmLevel: $('#alarmLevel').val(),
            notifyEnabled: $('#notifyEnabled').val(),
            notifyType: $('#notifyType').val() ? $('#notifyType').val().join(',') : '',
            notifyReceivers: $('#notifyReceivers').val(),
            remark: $('#remark').val()
        };
        
        // 确定是新增还是修改
        var url = '/warehouse/coldStorageThreshold';
        var type = 'POST';
        
        if (formData.thresholdId) {
            type = 'PUT';
        }
        
        // 发送请求
        $.ajax({
            url: url,
            type: type,
            contentType: 'application/json',
            data: JSON.stringify(formData),
            success: function(res) {
                if (res.code === 200) {
                    // 关闭模态框
                    $('#thresholdModal').modal('hide');
                    
                    // 刷新列表
                    loadThresholdList($('#warehouseSelect').val());
                    
                    // 提示成功
                    alert('保存成功！');
                } else {
                    alert('保存失败：' + res.msg);
                }
            },
            error: function() {
                alert('保存失败，请稍后重试！');
            }
        });
    }
    
    // 删除阈值设置
    function deleteThreshold(thresholdId) {
        $.ajax({
            url: '/warehouse/coldStorageThreshold/' + thresholdId,
            type: 'DELETE',
            success: function(res) {
                if (res.code === 200) {
                    // 刷新列表
                    loadThresholdList($('#warehouseSelect').val());
                    
                    // 提示成功
                    alert('删除成功！');
                } else {
                    alert('删除失败：' + res.msg);
                }
            },
            error: function() {
                alert('删除失败，请稍后重试！');
            }
        });
    }
    
    // 重置表单
    function resetForm() {
        $('#thresholdId').val('');
        $('#thresholdForm')[0].reset();
        $('#notifyType').selectpicker('deselectAll');
    }
    
    // 格式化日期时间
    function formatDateTime(dateTime) {
        if (!dateTime) return '';
        
        var dt = new Date(dateTime);
        
        var year = dt.getFullYear();
        var month = padZero(dt.getMonth() + 1);
        var day = padZero(dt.getDate());
        var hour = padZero(dt.getHours());
        var minute = padZero(dt.getMinutes());
        var second = padZero(dt.getSeconds());
        
        return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
    }
    
    // 补零
    function padZero(num) {
        return num < 10 ? '0' + num : num;
    }
}); 